package com.dc.business.datacollectbusiness.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import com.dc.business.datacollectbusiness.entity.Company;
import com.dc.business.datacollectbusiness.entity.CompanyUserRelationShip;
import com.dc.business.datacollectbusiness.entity.User;
import com.dc.business.datacollectbusiness.mapper.UserMapper;
import com.dc.business.datacollectbusiness.model.Result;
import com.dc.business.datacollectbusiness.model.UserModel;
import com.dc.business.datacollectbusiness.service.CompanyService;
import com.dc.business.datacollectbusiness.service.CompanyUserRelationShipService;
import com.dc.business.datacollectbusiness.service.UserService;
import com.dc.business.datacollectbusiness.utils.JwtUtil;
import com.dc.business.datacollectbusiness.utils.Md5Util;
import com.dc.business.datacollectbusiness.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@CrossOrigin
@RequestMapping("/api/user")
public class UserController {
    private LineCaptcha lineCaptcha;
    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private CompanyUserRelationShipService companyUserRelationShipService;

    @Autowired
    private CompanyService companyService;

    //线条验证码
    @GetMapping("/captcha")
    public void captcha(HttpServletResponse response) {
        RandomGenerator randomGenerator=new RandomGenerator("0123456789",4);
        this.lineCaptcha=CaptchaUtil.createLineCaptcha(200,100,5,50);
        this.lineCaptcha.setGenerator(randomGenerator);
        this.lineCaptcha.createCode();
        try (OutputStream outputStream = response.getOutputStream()){
            lineCaptcha.write(outputStream);
            outputStream.flush();
        }catch (IOException e){
            throw new RuntimeException(e);
        }
    }
    @GetMapping("/{username}/{password}/{code}")
    public Result login(@PathVariable String username, @PathVariable String password, @PathVariable String code) {
        if(this.lineCaptcha.equals(null)){
            return Result.error("验证码过期,请刷新验证码");
        }else {
            if (!this.lineCaptcha.verify(code)) {
                return Result.error("验证码错误！请重新输入");
            } else {
                if (userService.findUserByUsername(username) == null) {
                    return Result.error("用户不存在！");
                } else {
                    if (!Md5Util.md5(password).equals(userService.findUserByUsername(username).getPassword())) {
                        return Result.error("密码错误！");
                    } else {
                        Map<String, Object> claims = new HashMap<>();
                        claims.put("username", username);
                        claims.put("password", password);
                        String token = JwtUtil.createToken(claims);

                        //在redis中存储token,时间24小时
                        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
                        operations.set(token, token, 24, TimeUnit.HOURS);

                        UserModel userModel = new UserModel();
                        userModel.setToken(token);
                        userModel.setUserType(userService.findUserByUsername(username).getUserType());
                        return Result.success(userModel);
                    }
                }
            }
        }
    }
    @GetMapping("/getUser")
    public Result getUser() {
        Map<String,Object> map=new HashMap<>();
        map=ThreadLocalUtil.get();
        return Result.success(userService.findUserByUsername(map.get("username").toString()));
    }
    @GetMapping("/getUserpage")
    public Result pageAllUser(@RequestParam int page, @RequestParam int size,@RequestParam String companyName, @RequestParam String phoneNumber) {
//        try {
//            List<User>  list=userService.findAllUsers(page, size,companyName,phoneNumber);
//            int sum=userMapper.selectAllUsersum();
//            return Result.successfy(list,sum);
//        }catch (Exception e){
//            return Result.error(e.getMessage());
//        }
        //修改
        Map<String,Object> map=new HashMap<>();
        map= ThreadLocalUtil.get();
        User user=userService.findUserByUsername(map.get("username").toString());
        if(user.getUserType().equals("超级管理员")){
            List<User>  list=userService.findAllUsers(page, size,companyName,phoneNumber);
            int sum=userMapper.selectAllUsersum(companyName,phoneNumber);
            return Result.successfy(list,sum);
        }else {
            companyName=user.getCompanyName();
            List<User>  list=userService.findAllUsers(page, size,companyName,phoneNumber);
            int sum=userMapper.selectAllUsersum(companyName,phoneNumber);
            return Result.successfy(list,sum);
        }
    }
    @PostMapping("/addUser")
    public Result addUser(@RequestBody User user) {
        try {
            Map<String,Object> map=new HashMap<>();
            map=ThreadLocalUtil.get();
            User userupdate=userService.findUserByUsername(map.get("username").toString());

            if (!userupdate.getUserType().equals("超级管理员")){
                return Result.error("你不是超级管理员无法执行此操作");
            } else {
                if(userService.findUserByUsername(user.getUserName())!=null){
                    return Result.error("用户已存在");
                }else if(userService.getUsersumByCompanyName(user.getCompanyName())>=3){
                    return Result.error("该账号已存在三个");
                }else {
                    userService.insertUser(user);

                    if(user.getUserType().equals("普通用户")){
                        //添加关系
                        CompanyUserRelationShip companyUserRelationShip=new CompanyUserRelationShip();
                        //companyId
                        Company company=new Company();
                        company.setCompanyName(user.getCompanyName());
                        List<Company> companyList= companyService.getAllCompanyBytj(company);
                        int companyId=companyList.get(0).getCompanyId();
                        //userId
                        int userId= userService.getUseridByuserName(user.getUserName());
                        companyUserRelationShip.setUserId(userId);
                        companyUserRelationShip.setCompanyId(companyId);
//                    System.out.println(companyUserRelationShip);
                        companyUserRelationShipService.insertCompanyUserRelationShip(companyUserRelationShip);
                    }

                    return Result.success();
                }
            }

        }catch (Exception e){
            return Result.error(e.getMessage());
        }

    }
    @PutMapping("/updateUser")
    public Result updateUser(@RequestBody User user) {
        try {
            Map<String,Object> map=new HashMap<>();
            map=ThreadLocalUtil.get();
            User userupdate=userService.findUserByUsername(map.get("username").toString());
            if (!userupdate.getUserType().equals("超级管理员")){
                return Result.error("你不是超级管理员无法执行此操作");
            } else {
                userService.updateUser(user);
                return Result.success();
            }
        }catch (Exception e){
            return Result.error(e.getMessage());
        }
    }
    @PostMapping("/deleteall")
    public Result deleteUserByUserId(@RequestBody User user) {
        try {
            Map<String,Object> map=new HashMap<>();
            map=ThreadLocalUtil.get();
            User userdelete=userService.findUserByUsername(map.get("username").toString());
            if (!userdelete.getUserType().equals("超级管理员")){
                return Result.error("你不是超级管理员无法执行此操作");
            } else {
                boolean b=false;
                b=userService.deleteUserByIdall(user);
                if(b!=false){
                    return Result.success(b);
                }else {
                    return Result.error("删除失败");
                }
            }
        }catch (Exception e){
            return Result.error(e.getMessage());
        }


    }


    @GetMapping("/getbyid")
    public Result getUserByid(@RequestParam int userId) {
        User user=userService.getUserByid(userId);
        if(user==null){
            return Result.error("company not found");
        }else {
            return Result.success(user);
        }
    }

    //小程序

    //修改密码
    @GetMapping("/uppasswd")
    public Result upPasswd(@RequestParam String companyName,@RequestParam String userName,@RequestParam String newPassword,@RequestParam String newPassword2) {
//        System.out.println(companyName+","+userName+","+newPassword+","+newPassword2);
        if(newPassword.equals(newPassword2)){
            boolean b= userService.upPasswd(companyName,userName,newPassword);
            if(b){
                return Result.success("修改成功");
            }else {
                return Result.error("修改失败");
            }
        }else {
            return Result.error("两次密码不一致");
        }

    }


}
